package com.djhu.reactor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by zw on 2018/3/23.
 */
public class Selector {

    private BlockingQueue blockingQueue = new ArrayBlockingQueue(1024);

    private final Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();


    public List<Event> select() {
        return select(0);
    }

    private List<Event> select(int time) {
        lock.lock();
        try {
            if (time > 0){
                while (blockingQueue.isEmpty()){
                    condition.await(time,TimeUnit.SECONDS);
                }
            }else {
                while (blockingQueue.isEmpty()){
                    condition.await();
                }
            }
            List<Event> eventList = new ArrayList<>();
            blockingQueue.drainTo(eventList);
            return eventList;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return null;
    }


    public void addEvent(Event event){
        lock.lock();
        try {
            blockingQueue.add(event);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}